from pynput.keyboard import Key, Controller
import time
import pygetwindow as gw

# 创建键盘控制器实例
keyboard = Controller()

# 检查当前活动窗口标题是否包含 "原神"（不区分大小写）
def is_yuanshen_window_active():
    try:
        active_window = gw.getActiveWindow()
        if active_window is None:
            return False
        window_title = active_window.title
        return "原神" in window_title
    except:
        return False
    
def focus_window(title_keyword):
    """
    激活包含关键词的窗口
    :param title_keyword: 窗口标题中的关键词，如 "Chrome", "微信"
    """
    try:
        # 查找所有匹配的窗口（不区分大小写）
        windows = gw.getWindowsWithTitle(title_keyword)
        if not windows:
            print(f"❌ 未找到包含 '{title_keyword}' 的窗口")
            return False

        # 通常取第一个匹配的窗口
        window = windows[0]
        print(f"🎯 找到窗口: {window.title}")

        # 如果最小化，先恢复
        if window.isMinimized:
            window.restore()
            time.sleep(0.5)

        # 将窗口带到前台
        window.activate()  # 或使用 window.restore() + win32gui.SetForegroundWindow()
        print(f"✅ 已切换到: {window.title}")
        return True

    except Exception as e:
        print(f"❌ 切换失败: {e}")
        return False
    
focus_window("原神")
time.sleep(1)

# 乐谱
str_array1 = ["#|6|0.5", "+|3|0.25", "#|7|0.25", "#|7|1"]
str_array2 = ["#|7|0.5", "#|5|0.25", "#|6|0.25", "#|6|1"]
str_array3 = ["+|1|0.5", "#|7|0.5", "#|7|0.25", "#|6|0.5", "#|5|0.25"]
str_array4 = ["#|5|0.25", "#|6|0.5", "#|2|0.25", "#|3|1"]
str_array5 = ["#|6|0.25", "#|7|0.5", "+|1|0.25", "+|1|0.75", "#|6|0.5"]
str_array6 = ["+|3|0.5", "+|2|0.25", "#|6|0.25", "#|6|1"]
str_array7 = ["+|1|0.5", "#|7|0.25", "#|5|0.25",
              "#|5|0.25", "#|3|0.25", "#|7|0.5", "#|6|1.5"]
#孤单魂
str_array8 = ["+|1|0.75", "+|2|0.25", "+|3|1.25", "#|6|0.25",
              "+|3|0.25", "#|5|0.25", "#|5|0.75", "#|0|0.5"]

str_array9 = ["#|6|0.25", "#|7|0.25", "+|1|0.5", "#|7|0.25",
              "#|7|0.25", "#|6|0.25", "#|5|0.5", "#|2|0.25", "#|3|1.5", "#|0|0.5"]

str_array10 = ["+|1|0.25", "+|2|0.25", "+|3|0.25", "+|2|0.25", "+|3|0.25",
               "+|2|0.25", "+|3|0.5", "+|6|0.25", "+|6|0.25", "+|3|0.25", "+|2|0.25", "+|2|1.5"]

str_array11 = ["+|1|0.25", "#|7|0.25", "#|6|0.25", "#|5|0.25",
               "#|5|0.25", "#|3|0.25", "#|3|0.25", "#|7|0.25", "#|6|0.5", "#|6|1.5"]

str_array12 = ["+|6|1", "+|6|0.25", "+|3|0.5",
               "+|6|0.25", "+|5|0.25", "+|5|0.75", "+|5|1"]

str_array13 = ["+|2|0.25", "+|1|0.25", "+|2|0.25", "+|1|0.25",
               "#|6|0.25", "#|5|0.25", "+|5|0.5", "+|6|0.25", "+|3|0.25", "+|3|1"]

# 望明月心悲凉
str_array14 = ["+|6|1", "+|6|0.25", "+|3|0.5", "+|6|0.25", "+|5|0.25", "+|5|0.5", "+|6|0.25", "+|3|0.25", "+|2|0.25", "+|2|0.25",
               "+|1|0.25", "#|0|0.75", "#|6|0.25", "#|6|0.25", "#|5|0.25", "#|6|0.25", "+|3|0.25", "+|3|0.75", "+|3|1"]

# 过情关
str_array15 = ["+|6|1", "+|6|0.25", "+|3|0.5",
               "+|6|0.25", "+|5|0.25", "+|5|0.75", "+|5|1"]

str_array16 = ["+|2|0.25", "+|1|0.25", "+|2|0.5", "+|1|0.25",
               "#|6|0.25", "#|5|0.5", "+|5|0.25", "+|6|0.25", "+|3|0.25", "+|3|1.5"]

# 没有高两个八度的1(do),只能用高音区的1(do)
str_array17 = ["+|6|1", "+|6|0.25", "+|1|0.5", "+|7|0.25", "+|7|0.5", "+|6|0.25", "+|5|0.25", "+|5|0.75", "+|6|0.25",
               "#|0|0.5", "+|1|0.25", "#|6|0.25", "#|5|0.25", "#|6|0.5", "+|1|0.5", "+|1|0.25", "+|2|0.25", "+|1|1", "#|0|1"]

str_array18 = ["+|1|0.25", "+|2|0.25", "+|3|1", "+|3|0.25", "+|3|0.25",
               "+|3|0.5", "+|5|0.25", "#|5|0.25", "#|6|0.25", "#|5|0.25", "#|5|1"]

str_array19 = ["+|1|0.25", "#|7|0.25", "#|6|0.25", "#|5|0.25",
               "#|5|0.25", "#|3|0.25", "#|3|0.5", "#|7|0.25", "#|6|0.25", "#|6|1.5"]

# 合并所有元素并遍历
all_items = str_array1 + str_array2 + str_array3 + str_array4 + str_array5 + str_array6 + str_array7 + str_array8 + str_array9 + \
            str_array10 + str_array11 + str_array12 + str_array13 + str_array14 + \
            str_array15 + str_array16 + str_array17 + str_array18 + \
            str_array19 + str_array18 + str_array19

# BPM 和速度计算
bpm = 55
speed = round(60 / bpm, 2)

# 键盘映射
str_scale1 = ["a", "s", "d", "f", "g", "h", "j"]
str_scale2 = ["q", "w", "e", "r", "t", "y", "u"]
str_scale3 = ["z", "x", "c", "v", "b", "n", "m"]

# 遍历播放音符
for item in all_items:
    # 实时检查窗口是否仍然是 yuanshen
    if not is_yuanshen_window_active():
        print("警告：当前活动窗口已切换出 '原神'，程序终止。")
        break

    parts = item.split("|")
    key_char = ""
    duration = speed * float(parts[2])

    # 解析音符
    if parts[0] == "#":
        if parts[1] == "0":
            key_char = "0"
        else:
            key_char = str_scale1[int(parts[1]) - 1]
    elif parts[0] == "+":
        key_char = str_scale2[int(parts[1]) - 1]
    elif parts[0] == "-":
        key_char = str_scale3[int(parts[1]) - 1]

    # 模拟按键
    if key_char == "0":
        time.sleep(duration)
    else:
        keyboard.press(key_char)
        if duration >= speed * 0.75:
            time.sleep(duration)
            keyboard.release(key_char)
            time.sleep(0.05)
        else:
            time.sleep(0.03)
            keyboard.release(key_char)
            time.sleep(duration - 0.03)  # 补齐剩余时间